package service

import (
	"sdc/repository/db/model"

	"github.com/redis/go-redis/v9"
	"gorm.io/gorm"
)

type PermissionService struct {
	db          *gorm.DB
	redisClient *redis.Client
}
	
func NewPermissionService(db *gorm.DB, redisClient *redis.Client) *PermissionService {
	return &PermissionService{db: db, redisClient: redisClient}
}

// CheckPermission 检查用户是否有指定权限
func (s *PermissionService) CheckPermission(userID uint64, permCode string) bool {
	var count int64
	// 通过用户角色关联查询权限
	err := s.db.Model(&model.Permission{}).
		Joins("JOIN role_permissions ON permissions.id = role_permissions.permission_id").
		Joins("JOIN user_roles ON role_permissions.role_id = user_roles.role_id").
		Where("user_roles.user_id = ? AND permissions.code = ? AND permissions.status = 1",
			userID, permCode).
		Count(&count).Error

	if err != nil {
		return false
	}
	return count > 0
}

// GetUserPermissions 获取用户所有权限
func (s *PermissionService) GetUserPermissions(userID uint64) ([]model.Permission, error) {
	var permissions []model.Permission
	err := s.db.Model(&model.Permission{}).
		Select("DISTINCT permissions.*").
		Joins("JOIN role_permissions ON permissions.id = role_permissions.permission_id").
		Joins("JOIN user_roles ON role_permissions.role_id = user_roles.role_id").
		Where("user_roles.user_id = ? AND permissions.status = 1", userID).
		Find(&permissions).Error
	return permissions, err
}
